package com.bigfans.framework.es;

import com.bigfans.framework.utils.StringHelper;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.Settings.Builder;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class ElasticConnectionFactory {

	private volatile Client client;
	private Settings settings;

	private String cluster;
	private String host;
	private int port;

	public Client getConnection() {
		if (client == null) {
			synchronized (this) {
				if (client == null) {
					try {
						if (settings == null) {
							// 设置client.transport.sniff为true来使客户端去嗅探整个集群的状态，把集群中其它机器的ip地址加到客户端中
							Builder builder = Settings.builder();
//							builder.put("client.transport.sniff", true);
							if (StringHelper.isNotEmpty(cluster)) {
								builder.put("cluster.name", cluster);
							}
							settings = builder.build();
						}
						TransportClient transportClient = new PreBuiltTransportClient(settings)
								.addTransportAddress(new TransportAddress(InetAddress.getByName(host), port));

						if (transportClient.connectedNodes().size() == 0) {
							throw new Exception("can not connect to elasticsearch");
						}
						client = transportClient;
					} catch (Exception ex) {
						ex.printStackTrace();
					}
				}
			}
		}
		return client;
	}

	public void close() {
		if (client != null) {
			synchronized (this) {
				if (client != null) {
					this.client.close();
				}
			}
		}
	}

	public void addNewNode(String name) throws UnknownHostException {
		TransportClient transportClient = (TransportClient) client;
		transportClient.addTransportAddress(new TransportAddress(InetAddress.getByName(name), port));
	}

	public void removeNode(String name) throws UnknownHostException {
		TransportClient transportClient = (TransportClient) client;
		transportClient.removeTransportAddress(new TransportAddress(InetAddress.getByName(name), port));
	}

	public String getCluster() {
		return cluster;
	}

	public void setCluster(String cluster) {
		this.cluster = cluster;
	}

	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}
}
